from flask import Flask, request, jsonify
from datetime import datetime
import logging
import threading
import random

# 创建 Flask 应用
app = Flask(__name__)

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
last_call_time = None 
lock = threading.Lock()  # 线程锁，确保多线程环境下的线程安全
cameraids = ['1', '2', '3', '1977566226087546885', '1977554289358409728', '1977995792945909760', '1977665497952555008', '1977995792945909760']
videos = ['test2.mp4', 'test3.mp4', 'test5.mp4', 'test_cz1.mp4', 'test_cz2.mp4', 'test_cz3.mp4', 'test_cz4.mp4', 'test_video.mp4']

# 定义 GET 接口：/api/getCamera
@app.route('/api/getCamera', methods=['GET'])
def get_camera():
    """
    每隔 1 分钟返回 {"a": "a"}，其他时间返回 {}
    """
    r = random.randint(0, len(videos)-1)

    mock_data = {'id': cameraids[r],
                'rtsp': f'test/video/{videos[r]}',
                'name': 'name',
                'district':'district',
                'location':'latitude,longitude'
                }
    
    # 获取当前时间的秒数
    global last_call_time
    current_time = datetime.now()
    
    with lock:  # 确保线程安全
        # 判断是否是每分钟的整点时刻（秒数为 0）
        if last_call_time is None or (current_time - last_call_time).total_seconds() >= 60:
            # 返回 {"a": "a"}
            last_call_time = current_time
            return {'data':mock_data}
        else:
            # 返回空报文 {}
            return jsonify({})

# 定义 POST 接口：/api/reportEvent
@app.route('/api/reportEvent', methods=['POST'])
def report_event():
    """
    接收 JSON 报文，打印到日志，并返回 {"result": "ok"}
    """
    try:
        # 获取请求体中的 JSON 数据
        data = request.get_json()
        
        # 检查是否接收到有效的 JSON 数据
        if not data:
            return jsonify({"error": "Invalid JSON data"}), 400
        
        # 打印 JSON 数据到控制台（模拟日志输出）
        print("Received POST data:", data)
        logging.info(f"Received POST data: {data}")
        
        # 返回成功响应
        return jsonify({"result": "ok"})
    
    except Exception as e:
        # 如果发生错误，返回错误响应
        logger.error(f"Error in report_event: {str(e)}")
        return jsonify({"error": str(e)}), 500

# 启动 Flask 应用
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5555, debug=True)